package org.ucas.faker.web.controller.visualization;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.ucas.faker.web.Config.VisualConfig;
import org.ucas.faker.web.controller.BaseController;
import org.ucas.faker.web.dto.CarryDto;
import org.ucas.faker.web.dto.PageDto;
import org.ucas.faker.web.dto.ResponseDto;
import org.ucas.faker.web.fetcher.FetchExecutor;
import org.ucas.faker.web.fetcher.FetchReqBuilder;
import org.ucas.faker.web.fetcher.FetchRequest;
import org.ucas.faker.web.fetcher.FetchResult;
import org.ucas.faker.web.service.PatentService;
import org.ucas.faker.web.service.Visualization.CallbackService;
import org.ucas.faker.web.service.Visualization.DataService;
import org.ucas.faker.web.service.Visualization.OptionService;
import org.ucas.faker.web.service.Visualization.VisualService;
import org.ucas.faker.web.service.Visualization.json.JsonUtil;
import org.ucas.faker.web.utils.model.RawPatent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
public class CallbackController extends BaseController {

    @Autowired private FetchExecutor fetcher;
    @Autowired private DataService dataService;
    @Autowired private CallbackService callbackService;
    @Autowired private PatentService patentService;


    @RequestMapping(value = "/graph/callback/special") //, method = RequestMethod.POST
    @ResponseBody
    public String specialCallback(@RequestParam(value = "ids_json") String ids_json,
                                  @RequestParam(value = "graph_type", required = false) String graph_type){
        JSONArray idsJson = JSON.parseArray(ids_json);
        List<Long> idList = JsonUtil.<Long>jsonArrayToList(idsJson);
        List<RawPatent> patentList = patentService.loadBatch(idList);

        return "success";
    }

    @ResponseBody
    @RequestMapping(value = "/graph/callback/general", method = RequestMethod.POST)
    public ResponseDto generalCallback(@RequestParam(value = "graph_message", required = true) String graph_json,
                                  @RequestParam(value = "callback_message", required = true) String callback_json,
                                  @RequestParam(value = "graph_type", required = false) String graph_type){
    	graph_type(graph_type);
    	graph_json(graph_json);
    	callback_json(callback_json);
    	return ResponseDto.OK;
    }

    @ResponseBody
    @RequestMapping(value = "/graph/patents", method = RequestMethod.POST)
    public PageDto<RawPatent> generalPatents(@RequestParam(value = "pageNumber", required = false) Integer page){
    	if(page==null) page = 1;
    	String graph_json = graph_json();
    	String callback_json = callback_json();
    	List<RawPatent> patents = new ArrayList<>();
    	System.out.println("................"+graph_type());
    	if(graph_type()==null) {
    		patents = callBackFunction_common(graph_json,callback_json,page);
    	}else if(graph_type().equals("city")) {
    		patents = callBackFunction_city(callback_json,page);
    	}else if(graph_type().equals("matrix")) {
    		patents = callBackFunction_techAndEffMatrix(callback_json,page);
    	}else if(graph_type().equals("heatmap")) {
    		patents = callBackFunction_heatMap(callback_json,page);
    	}else if(graph_type().equals("fishbone")) {
    		patents = callBackFunction_fishbone(callback_json,page);
    	}
    	
        return PageDto.ofList(patents, patents.size(), page, 20);
    }
    public List<RawPatent> callBackFunction_common(String graph_json,String callback_json,int page) {
    	long depotId = currentDepotId();
        JSONObject graphJson = JSONObject.parseObject(graph_json);
        JSONObject callbackJson = JSONObject.parseObject(callback_json);
        FetchReqBuilder requestBuilder = FetchReqBuilder.instance().depot(depotId).select("id");
        dataService.parseConstraint(graphJson, requestBuilder);
        callbackService.handleGeneralCallback(graphJson, callbackJson, requestBuilder);
        //分页限制
        //requestBuilder.limit((page-1)*20, 20);

        FetchResult result = fetcher.fetch(requestBuilder.build());
        List<Long> ids = result.column("id");
        System.out.println("fetch size="+ids.size()+"\tstat="+callbackJson.get("data"));
        List<RawPatent> patents = patentService.loadBatch(ids);
        return patents;
    }
    public List<RawPatent> callBackFunction_techAndEffMatrix(String callback_json,int page) {
    	String index= callback_json;
    	
    	HashMap<String,List<Long>> patendIdListMap=graph_ids_map();
    	System.out.println(index);
    	List<Long> patentIdList = patendIdListMap.get(index);
    	
//    	Iterator<Entry<String, List<Long>>> iter = patendIdListMap.entrySet().iterator();
//        while (iter.hasNext()) {
//        	Map.Entry entry = (Map.Entry) iter.next();
//        	String key = (String) entry.getKey();
//        	List<Long> val = (List<Long>) entry.getValue();
//        	if(key.contains(index)) {
//        		patentIdList = val;
//        	}
//        }
    	
        /*String column="id";
        String column2="apr";
        
        FetchReqBuilder requestBuilder = FetchReqBuilder.instance().depot(currentDepotId());
   	   	requestBuilder.select(column).not_null(column).eq(column2, city);
   	   	requestBuilder.limit((page-1)*20, 20);
   	   	FetchRequest req = requestBuilder.build();
   	   	
        FetchResult result = fetcher.fetch(req);
        List<Long> ids = result.column(column);*/
//    	List<Long> ids = new ArrayList<>();
//    	for(int start = (page-1)*20;start<page*20&&start<patentIdList.size();start++) {
//    		ids.add(patentIdList.get(start));
//    	}
//    	
//        for(long l:ids) {
//        	System.out.print(l+",");
//        }   
        
        List<RawPatent> patents = patentService.loadBatch(patentIdList);
        return patents;
    }
    public List<RawPatent> callBackFunction_city(String callback_json,int page) {
    	String city= callback_json;
  	    String[] provinceNameFull= {"北京市","天津市","河北省","山西省","内蒙古自治区","辽宁省","吉林省","黑龙江省","上海市","江苏省",
  			  "浙江省", "安徽省","福建省","江西省","山东省","河南省","湖北省","湖南省","广东省","广西壮族自治区","海南省","重庆市","四川省","贵州省","云南省","西藏自治区","陕西省","甘肃省",
  			  "青海省","宁夏回族自治区","新疆维吾尔自治区","台湾省","香港特别行政区","澳门特别行政区","南海诸岛"};
        for(int j=0;j<provinceNameFull.length;j++) {
        	if(provinceNameFull[j].contains(city)) {
      			city=provinceNameFull[j];
      		 }
      	}
        String column="id";
        String column2="apr";
        
        FetchReqBuilder requestBuilder = FetchReqBuilder.instance().depot(currentDepotId());
   	   	requestBuilder.select(column).not_null(column).eq(column2, city);
   	   	//requestBuilder.limit((page-1)*20, 20);
   	   	FetchRequest req = requestBuilder.build();
   	   	
        FetchResult result = fetcher.fetch(req);
        List<Long> ids = result.column(column);
        List<RawPatent> patents = patentService.loadBatch(ids);
        return patents;
    }
    
    public List<RawPatent> callBackFunction_heatMap(String callback_json,int page) {
    	String index= callback_json;
    	List<String> patentIdList=JSONObject.parseArray(index, String.class);
    	
    	//HashMap<String,List<Long>> patendIdListMap=graph_ids_map();
    	System.out.println(patentIdList);
    	
//    	Iterator<Entry<String, List<Long>>> iter = patendIdListMap.entrySet().iterator();
//        while (iter.hasNext()) {
//        	Map.Entry entry = (Map.Entry) iter.next();
//        	String key = (String) entry.getKey();
//        	List<Long> val = (List<Long>) entry.getValue();
//        	if(key.contains(index)) {
//        		patentIdList = val;
//        	}
//        }
    	
        /*String column="id";
        String column2="apr";
        
        FetchReqBuilder requestBuilder = FetchReqBuilder.instance().depot(currentDepotId());
   	   	requestBuilder.select(column).not_null(column).eq(column2, city);
   	   	requestBuilder.limit((page-1)*20, 20);
   	   	FetchRequest req = requestBuilder.build();
   	   	
        FetchResult result = fetcher.fetch(req);
        List<Long> ids = result.column(column);*/
    	List<Long> ids = new ArrayList<>();
    	//for(int start = (page-1)*20;start<page*20&&start<patentIdList.size();start++) {
    	for(int start = 0;start<patentIdList.size();start++) {
    		ids.add(Long.parseLong(patentIdList.get(start)));
    	}
    	
        for(long l:ids) {
        	System.out.print(l+",");
        }   
        
        List<RawPatent> patents = patentService.loadBatch(ids);
        return patents;
    }
    
    public List<RawPatent> callBackFunction_fishbone(String callback_json,int page) {
    	String index= callback_json;
    	List<String> patentIdList=JSONObject.parseArray(index, String.class);
    	
    	//HashMap<String,List<Long>> patendIdListMap=graph_ids_map();
    	System.out.println(patentIdList);
    	
//    	Iterator<Entry<String, List<Long>>> iter = patendIdListMap.entrySet().iterator();
//        while (iter.hasNext()) {
//        	Map.Entry entry = (Map.Entry) iter.next();
//        	String key = (String) entry.getKey();
//        	List<Long> val = (List<Long>) entry.getValue();
//        	if(key.contains(index)) {
//        		patentIdList = val;
//        	}
//        }
    	
        /*String column="id";
        String column2="apr";
        
        FetchReqBuilder requestBuilder = FetchReqBuilder.instance().depot(currentDepotId());
   	   	requestBuilder.select(column).not_null(column).eq(column2, city);
   	   	requestBuilder.limit((page-1)*20, 20);
   	   	FetchRequest req = requestBuilder.build();
   	   	
        FetchResult result = fetcher.fetch(req);
        List<Long> ids = result.column(column);*/
    	List<Long> ids = new ArrayList<>();
    	//for(int start = (page-1)*20;start<page*20&&start<patentIdList.size();start++) {
    	for(int start = 0;start<patentIdList.size();start++) {
    		ids.add(Long.parseLong(patentIdList.get(start)));
    	}
    	
        for(long l:ids) {
        	System.out.print(l+",");
        }   
        
        List<RawPatent> patents = patentService.loadBatch(ids);
        return patents;
    }
    
}
